package com.jxpanda.spring.module.wechat.config.properties;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * CorpProperties 类是一个记录类，用于存储企业属性以及其相关的应用属性。
 *
 * @param enable     是否启用企业微信。
 * @param corpId     企业微信的唯一标识符。
 * @param privateKey 企业微信的私钥。
 * @param publicKey  企业微信的公钥。
 * @param applets    企业微信下的应用属性。
 */
public record CorpProperties(boolean enable,
                             String corpId,
                             String privateKey,
                             String publicKey,
                             Map<String, CorpAppletProperties> applets) {

    public CorpProperties(boolean enable, String corpId, String privateKey, String publicKey, Map<String, CorpAppletProperties> applets) {
        this.enable = enable;
        this.corpId = corpId == null ? "" : corpId;
        this.privateKey = privateKey == null ? "" : privateKey;
        this.publicKey = publicKey == null ? "" : publicKey;
        Map<String, CorpAppletProperties> tempApplets = Collections.emptyMap();
        if (!ObjectUtils.isEmpty(applets)) {
            tempApplets = applets.entrySet().stream().map(entry -> {
                        String appName = entry.getKey();
                        CorpAppletProperties value = entry.getValue();
                        return new CorpAppletProperties(appName, value.getAppId(), value.getAppSecret(), value.getCallbackToken(), value.getCallbackEncodingAESKey());
                    })
                    .collect(Collectors.toMap(CorpAppletProperties::getName, it -> it));
        }
        this.applets = tempApplets;
    }


    @Data
    @EqualsAndHashCode(callSuper = true)
    public static class CorpAppletProperties extends AppletProperties {

        private String callbackToken;
        private String callbackEncodingAESKey;


        public CorpAppletProperties(String name, String appId, String appSecret, String callbackToken, String callbackEncodingAESKey) {
            this.name = name == null ? "" : name;
            this.appId = appId == null ? "" : appId;
            this.appSecret = appSecret == null ? "" : appSecret;
            this.callbackToken = callbackToken == null ? "" : callbackToken;
            this.callbackEncodingAESKey = callbackEncodingAESKey == null ? "" : callbackEncodingAESKey;
        }

    }

}

